package tcc.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import tcc.dao.UsuarioDAO;
import tcc.model.Usuario;
import tcc.util.MD5;
import tcc.util.Site;

@WebServlet(urlPatterns = { "/login" })
public class LoginCtrl extends HttpServlet {
	private static final long serialVersionUID = 5651358763261849436L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Map<String, String[]> params = req.getParameterMap();

		// DESLOGAR: remove a variavel usuario
		if (params.get("logout") != null) {
			req.getSession().removeAttribute("usuario");
			resp.sendRedirect("./");
			return;
		}

		req.setAttribute("content", "login.jsp");
		req.setAttribute("usuario", req.getSession().getAttribute("usuario"));
		req.getRequestDispatcher("/template.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		Map<String, String[]> params = req.getParameterMap();
		
		UsuarioDAO usuarioDAO = new UsuarioDAO();
		Usuario u = usuarioDAO.recuperarPorEmail(params.get("email")[0]);
		
		
		
		
		if (u == null) {
			resp.sendRedirect("./login?erro=dados");
			return;
		}

		String senhamd5 = MD5.passwd2MD5(params.get("senha")[0]);

		if (senhamd5.compareTo(u.getSenhaMD5()) == 0) {
			req.getSession().setAttribute("usuario", u);
		} else {
			resp.sendRedirect("./login?erro=dados");
			return;
		}

		resp.sendRedirect("./");

	}
}
